package org.spring.boot.fusion.auth.sso.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.spring.boot.fusion.auth.sso.service.FusionPermissionsService;
import org.spring.boot.fusion.common.constant.ConstantAttribute;
import org.spring.boot.fusion.common.exception.ServiceErrorStatus;
import org.spring.boot.fusion.common.response.ResponseData;
import org.spring.boot.fusion.common.tools.JsonTool;
import org.spring.boot.fusion.security.properties.FusionTokenProperties;
import org.spring.boot.fusion.security.tools.FusionCheckUrlTools;
import org.springframework.http.HttpStatus;
import org.springframework.web.filter.OncePerRequestFilter;

import lombok.Data;
import lombok.EqualsAndHashCode;

@Data
@EqualsAndHashCode(callSuper = false)
public class FusionPermissionsValidateFilter extends OncePerRequestFilter {

	private FusionTokenProperties tokenProperties;

	private FusionPermissionsService permissionsService;

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		ResponseData error = ResponseData.ERROR(ServiceErrorStatus.NOT_PERMISSIONS);
		if (tokenProperties.isPermissionsAuth()) {
			if (FusionCheckUrlTools.checkUrl(request.getRequestURI(), tokenProperties,request)) {
				filterChain.doFilter(request, response);
			} else {
				if (permissionsService.checkHavePermissions(request)) {
					filterChain.doFilter(request, response);
				} else {
					response.setStatus(HttpStatus.UNAUTHORIZED.value());
					response.setContentType(ConstantAttribute.JSON_TYPE_UTF8);
					response.getWriter().write(JsonTool.ObjectToJson(error));
				}
			}
		} else {
			filterChain.doFilter(request, response);
		}
	}

}
